<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('APPID', 'wx55b2602cacf4aef1');
define('APPSECRET', 'bb172354fad414c35415f30370feff65');

/**
 * 公用函数库
 *
 * @author www.dingwei.cn
 */
function wechat(){
    //加载微信包
    require_once APPPATH.'libraries/wechat/Weixin.class.php';

    return Weixin::getWechat();
}

/**
 * 验证权限
 * @param string $key
 * @param string $module
 * @return	boolean
 */
function adminAuthority($key, $module){
	return get_instance()->adminAuthority($key, $module);
}

/**
 * 生成验证码  区(字母两位-时分秒-随机数3位) AA - 102356 - 255
 * @return string
 */
function makeCode($id = ''){
    $Castr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
    $CAstr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

    $len = strlen($id);
    $begin = substr(99999,0,-$len);
    $end = substr(10000,0,-$len);

    /* 	for ($a = 0; $a < 1000;$a++){
            $str = $CAstr[rand(0,25)].$CAstr[rand(0,25)].$id;
            if ($begin && $end){
                $str .= rand($begin,$end);
            }
            echo $str.'<br>';
        }  */

    $str = $CAstr[rand(0,25)].$CAstr[rand(0,25)].$id;
    if ($begin && $end){
        $str .= rand($begin,$end);
    }
    return $str;
}


function HASSET($value,$defalut = ''){
    return isset($value)?$value:$defalut;
}

//生成二维码图片
function makeCodeImg($fileName,$code,$fname = ''){
    include APPPATH."libraries/PHPqrcode/phpqrcode.php";
    $value = $fname.$code; //二维码内容
    $errorCorrectionLevel = 'L';//容错级别
    $matrixPointSize = 4;//生成图片大小

    $code_url = $fileName.'_'.$code.'.png';
    $path = 'uploads/code/'.date('Ymd').'/';
    if ( ! file_exists($path)){
        mkdir($path,0777,true);
    }
    $path = $path.$code_url;
    \QRcode::png($value, $path, $errorCorrectionLevel, $matrixPointSize, 2);

    return $path;

}

/**
 * 时分秒 换成 秒
 * @param string $time 时间[10:21:54]
 * @return $the  切换  false 时间转换  true 秒转时间
 * @return number
 * @author zyl
 */
function time_to_second($time,$the = FALSE){
    if ($the){
        $hours = floor($time / 3600);
        $minutes = floor(($time - $hours * 3600) / 60);
        $second = floor(($time - $hours * 3600 - $minutes * 60));
        if ($hours > 24){
            $hours = '00';
        }
        $val = ($hours >= 10 ? $hours: '0'.$hours).':'.($minutes >= 10 ? $minutes : '0'.$minutes);//.':'.($second > 10 ? $second : '0'.$second);
    }else{
        $hours = date('H',strtotime($time));
        $minutes = date('i',strtotime($time));
        $second = date('s',strtotime($time));
        $val = ($hours * 3600) + ($minutes * 60) + $second;
    }
    return $val;
}

/**
 * 快递鸟对象获取
 */
function KDNiao(){
    include APPPATH."libraries/kdniao/Kdniao.php";
    return Kdniao::getObject(getCustomConfig('kdn_Api_ID'), getCustomConfig('kdn_Api_Key'));
}

/**
 * 云通讯发送短信
 * 注册短信：模板id:76790
 * 找回密码：模板id:76794
 * 支付密码：模板id:76796
 * @author zyl
 */
function QCsendSms($mobile,$templId,$params){
    include APPPATH."libraries/qcloudsms/SmsSender.php";
    include APPPATH."libraries/qcloudsms/SmsVoiceSender.php";

    $singleSender = new Qcloud\Sms\SmsSingleSender(getCustomConfig('qc_appid'),getCustomConfig('qc_key'));
    $result = $singleSender->sendWithParam("86", $mobile, $templId, $params, '', "", "");
    $rsp = json_decode($result,true);

    if($rsp['result'] == 0){
        return true;
    }
    return false;
}

/**
 * 获取子集[递归][来自Youzl方法]
 * @param integer $pid      父级ID
 * @param array   $data     原始数据
 * @param string  $id       做为id的字段名称
 * @param string  $pid      做为pid的字段名称
 * @param string  $child    做为child的字段名称
 * @return array[][]
 */
function getchild($pid,$data,$id = 'id',$parent = 'pid',$child = 'child'){
    $DATA = array();
    foreach ($data as $k=>$v){
        if($v[$parent] == $pid){
            $v[$child] = getchild($v[$id], $data, $id, $parent, $child);
            $DATA[] = $v;
        }
    }

    return $DATA;
}

/*
  16-19 位卡号校验位采用 Luhm 校验方法计算：
    1，将未带校验位的 15 位卡号从右依次编号 1 到 15，位于奇数位号上的数字乘以 2
    2，将奇位乘积的个十位全部相加，再加上所有偶数位上的数字
    3，将加法和加上校验位能被 10 整除。
*/
function check_bankCard($card_number){
    $arr_no = str_split($card_number);
    $last_n = $arr_no[count($arr_no)-1];
    krsort($arr_no);
    $i = 1;
    $total = 0;
    foreach ($arr_no as $n){
        if($i%2==0){
            $ix = $n*2;
            if($ix>=10){
                $nx = 1 + ($ix % 10);
                $total += $nx;
            }else{
                $total += $ix;
            }
        }else{
            $total += $n;
        }
        $i++;
    }
    $total -= $last_n;
    $x = 10 - ($total % 10);
    if($x == $last_n){
        return true;
    }else{
        return false;
    }
}


/**
 * 后台管理
 *
 * 自动生成按钮，自动进行权限判断隐藏
 *
 * @param 	array 	$config		配置
 * @return	string
 */
function adminCreateBtn($config,$group = TRUE){

    $data = array();
    if(isset($config[0])){
        foreach ($config as $v){
            $btn = adminCreateBtn($v);
            if($btn){
                $data[] = adminCreateBtn($v);
            }
        }

        if(count($data) == 1){
            return $data[0];
        }

        $btn = '';
        foreach ($data as $k => $v){
            if ($group){
                if($k == 0){
                    $btn .= '<div class="btn-group">'.$v.'
					<button data-toggle="dropdown" class="btn btn-default dropdown-toggle btn-xs" type="button">
					<i class="fa fa-angle-down"></i></button><ul role="menu" class="dropdown-menu pull-right">';
                }else{
                    $btn .= '<li>'.$v.'</li>';
                }
            }else{
                if($k == 0){
                    $btn .= '<div class="btn-group" style="margin-top: -2px;">'.$v;
                }else{
                    $btn .= $v;
                }

            }
        }

        if ($group){
            $btn .= '</ul></div>';
        }else{
            $btn .= '</div>';
        }

        return $btn;
    }else{
        if(isset($config['permissions'])){
            if( ! adminAuthority($config['permissions']['key'], $config['permissions']['module'])){
                return '';
            }
        }
        $class = '';
        if(isset($config['class'])){
            $class = $config['class'];
        }

        $href = 'javascript:void(0)';
        if(isset($config['href'])){
            $href = $config['href'];
        }

        $icon = '';
        if(isset($config['icon'])){
            $icon = $config['icon'];
        }

        $attr = '';
        if(isset($config['attr'])){
            foreach ($config['attr'] as $k => $v){
                $attr .= ' '.$k.'="'.$v.'" ';
            }
        }

        $tag = 'a';
        if( ! empty($config['tag'])){
            $tag = $config['tag'];
        }

        $label = '';
        if( ! empty($config['label'])){
            $label = $config['label'];
        }

        return '<'.$tag.$attr.'>'.' '.$icon.' '.$label.'</'.$tag.'>';
    }
}

/**
 * 送达时间列表
 * @param integer $star 开始时间<时间戳>
 * @param integer $end  结束时间<时间戳>
 * @param integer $forecast 预计时间
 * @param integer $other 其他时间
 * @param integer $interval 间隔时间
 * @return array
 */
function arriveTime($star,$end,$forecast,$other,$interval,$day = 1){

    if ($interval < 5){
        throw  new ErrorException('(arriveTime)间隔时间必须大于5s,不然会计算繁重!');
    }

    $tTime = [];//时间数组
    $tempTime = $star + ( $forecast * 60 ) + ( $other * 60 ); //开始时间 + 预计时间 + 其他时间
    $endDate = strtotime('+'.($day-1).'day',$end); //结束日期

    $starHis = date('His',$star);
    $endHis = date('His',$end);

    while ($tempTime < ( $endDate + ( $interval * 60 ) ) ){
        $nowHis = date('His',$tempTime);
        if ($nowHis > $starHis && $nowHis <= $endHis + ( $interval * 60 ) ){
            //满足条件的时间
//            $tTime[] = date('Y年m月d日 H:i:s',$tempTime);
            if ($tempTime > strtotime('+1day',$star)){
                $tTime['otherday'][] = date('H:i',$tempTime);
            }else{
                $tTime['today'][] = date('H:i',$tempTime);
            }
        }
        $tempTime = $tempTime + ( $interval * 60 );
    }
    return $tTime;
}

/**
 * 生成送达时间 间隔时间段
 * @param unknown $time  营业时间段
 * @param unknown $forecast 商家接单时限
 * @param unknown $other    配送接单时限
 * @param unknown $expect    商家预计送达时间
 * @param unknown $interval 时间间隔(20分钟)
 * @param number $day
 * @return array|number
 */
function appArriveTime($time,$forecast,$other,$expect,$interval,$day = 1,$wx = FALSE){
    $star = 'business_time_start';
    $end = 'business_time_end';

    if ( ! $time || (!$time[0]['business_time_start'] && !$time[0]['business_time_end'])){
        $time = array(
            ['business_time_start'=>0,'business_time_end'=>24 * 3600],
        );

    }
    if(!$expect){
        $expect = 0;
    }
    $tTime = ['today' => [],'other' =>[]];//时间数组
    $tWxTime = ['today' => [],'other' =>[]];//微信时间控件
    $total = (($forecast + $other + $expect)* 60);
    $now = time_to_second(date('Hi'));

    foreach ($time as $k=>$vTime){

        //第一天
        if ($vTime[$star] < $now){
            //如果时间小于当前时间
            $vTime[$star] = $now;
        }

        $starTime = $vTime[$star] + $total; //第一个时间

        for($i=$starTime ;$i<=$vTime[$end]+ $total ; $i=$i+60*$interval){
            if($i != $starTime){
                //分钟数为10的整数倍
                $mitute = date('i',$i);
                $unit   = $mitute % 10;//个位分钟数
                if($unit != 0){
                    $offset = 10 - $unit;
                    $i = $offset*60 + $i;
                }
            }
            $tTime['today'][] = time_to_second($i,true);
            if ($wx){
                $tWxTime['today'][] = ['label'=>time_to_second($i,true),'value'=>time_to_second($i,true)];
            }
        }

    }
    //今天存在送达时间，就不返回明天
    if($tWxTime['today']){
        $tWxTime['other'] = [];
        return $tWxTime;
    }
    if($tTime['today']){
        $tTime['other'] = [];
        return $tTime;
    }
    $starTime = 0;
    foreach ($time as $k=>$vTime){

        $starTime = $vTime[$star] + $total; //第一个时间

        for($i=$starTime ;$i<=$vTime[$end]+ $total ; $i=$i+60*$interval){
            //分钟数为10的整数倍
            $mitute = date('i',$i);
            $unit   = $mitute % 10;//个位分钟数
            if($unit != 0){
                $offset = 10 - $unit;
                $i = $offset*60 + $i;
            }
            $tTime['other'][] = time_to_second($i,true);

            if ($wx){
                $tWxTime['other'][] = ['label'=>time_to_second($i,true),'value'=>time_to_second($i,true)];
            }
        }
    }

    if ($wx){
        return $tWxTime;
    }
    return $tTime;
}

/**
 * 计算两个坐标点的距离
 * @param number $latitude		起始纬度
 * @param number $longitude		起始经度
 * @param number $latitude2		结束纬度
 * @param number $longitude2	结束经度
 * @return number  单位：m
 */
function dsitance($latitude, $longitude, $latitude2, $longitude2){

    if($latitude > $latitude2){
        return ceil((acos(sin(($latitude * 3.1415) / 180 )
                    *sin(($latitude2 * 3.1415) / 180 ) + cos(($latitude * 3.1415) / 180 ) * cos(($latitude * 3.1415) / 180 )
                    * cos(($longitude * 3.1415) / 180 - ($longitude2 * 3.1415) / 180 ) ) * 6380 ) * 1000);

    }else{
        return ceil((acos(sin(($latitude2 * 3.1415) / 180 )
                    *sin(($latitude * 3.1415) / 180 ) + cos(($latitude2 * 3.1415) / 180 ) * cos(($latitude2 * 3.1415) / 180 )
                    * cos(($longitude2 * 3.1415) / 180 - ($longitude * 3.1415) / 180 ) ) * 6380 ) * 1000);

    }
}

/**
 *距离计算 单位：m
 */
function getDistance($lat1,$lng1,$lat2,$lng2,$decimal=3){
    $EARTH_RADIUS=6378.137;     //地球半徑,假設地球是規則的球體
    $PI=3.1415926;              //圓周率
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $a       = $radLat1 - $radLat2;
    $b       = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s*1000);

    return round($s,$decimal);

}
/**
 * 日期格式化
 *
 * @param	$time	时间戳
 * @return	string
 */
function dateFormat($number, $showTime = false){

    if($showTime){
        return date('Y-m-d H:i:s', $number);
    }
    return date('Y-m-d', $number);
}

/**
 * 显示时间
 *
 * @param	$time	时间戳
 * @return	string
 */
function showBeautifulTimeForMat($time){

    if( ! $time){
        return '';
    }

    $d = time() - $time;

    if($d < 60){
        return floor($d).'秒前';
    }elseif($d > 60 && $d < 3600){
        return floor($d / 60).'分钟前';
    }elseif($d / 3600 < 24){
        return floor($d / 3600).'小时前';
    }elseif($d / 3600 >= 24 && $d / 3600 < 24 * 30){
        return floor($d /3600/ 24).'天前';
    }elseif($d / 3600 >= 24 * 30 && $d / 3600 < 24 * 365){
        return floor($d / 3600 / 24 / 30).'个月前';
    }elseif($d / 3600 >= 24 * 365){
        return floor($d / 3600 / 24 / 365).'年前';
    }

    return '';
}

/**
 * 获取url
 *
 * @param	string	$uri	uri
 * @param	 string		$port		传入的端口
 * @return	string
 */
function getUrl($uri, $port = '', $terminal = ''){
    $ci = get_instance();
    $path = $ci->uriDir;
    $terminal = $terminal ? $terminal : $ci->terminal;
    if($ci->port == 'area' || $port == 'area'){
        $path = '';
    }

    if($port && $port != 'area'){
        $path = $port;
    }

    if($terminal == 'pc'){
        if($ci->terminal){
            return str_replace($ci->terminal.'/', '', site_url($path.'/'.$uri));
        }
        return site_url($path.'/'.$uri);
    }elseif($terminal){
        return str_replace($ci->terminal.'/', $terminal.'/', site_url($path.'/'.$uri));
    }

    return str_replace('pc/', '', site_url($path.'/'.$uri));
}


/**
 * 获取自定义配置
 *
 * @param	string	$key		配置key，多个已“,”隔开
 * @param	string	$fileName	配置文件名称
 * @return	mixed
 */
function getCustomConfig($key = '', $fileName = 'config'){

    if($fileName != ''){

        $ci = get_instance();
        $file = 'custom/'.$fileName;
        $ci->config->load($file, TRUE);
        $configs = config_item($file);

        if(empty($configs)) return null;
        if(strpos($key, ',') !== false){

            $data = array();
            $tA = explode(',', $key);
            foreach ($tA as $v){
                if($v){
                    $data[$v] = isset($configs[$v]) ? $configs[$v] : null;
                }else{
                    $data[$v] = null;
                }
            }

            return $data;
        }else if($key){
            return isset($configs[$key]) ? $configs[$key] : null;
        }else if( ! $key){
            return $configs;
        }
    }

    return null;
}

/**
 * 加密密码
 * @param	string	$password	密码
 * @return	string
 */
function setPassword($password){
    $key = config_item('encryption_key');
    $str = $password.$key;
    $str1 = substr($str, 4, 10);
    return encryption($str1.$str);
}

/**
 * 加密
 *
 * @param	string	$str	加密字符
 * @return	string
 */
function encryption($str){

    if($str){
        get_instance()->load->helper('security');
        return do_hash($str, 'sha1');
    }

    return '';
}

/**
 * 解密
 *
 * @param	string $string	要解密不的字符
 * @return	string
 */
function decode($string, $key = ''){

    if($string){
        $ci = get_instance();
        $ci->load->library('encryption');
        $ci->encryption->initialize(array(
            'driver' => 'openssl',
            'cipher' => 'aes-256',
            'mode' => 'ctr',
            'key' => $key
        ));
        return $ci->encryption->decrypt($string);
    }
    return '';
}

/**
 * 加密
 *
 * @param	string $userId	微信用户id
 * @return	string
 */
function encode($string, $key = ''){

    if($string){
        $ci = get_instance();
        $parma = array(
            'driver' => 'openssl',
            'cipher' => 'aes-256',
            'mode' => 'ctr',
            'key' => $key
        );
        $ci->load->library('encryption');
        $ci->encryption->initialize($parma);
        return $ci->encryption->encrypt($string);
    }

    return '';
}

/**
 * 加载界面静态插件
 *
 * @param	string	$plugins	插件名称 ，多个以“,”隔开
 * @return	string
 */

function loadStaticPlugin($plugins){

    $str = '';
    $tA = array();
    if($plugins){
        $tA = getCustomConfig($plugins, 'static_plugin');
    }
    if( ! empty($tA)){

        $baseUrl = base_url('static').'/';
        foreach ($tA as $v){
            if(is_array($v)){
                foreach ($v as $vv){

                    $ext = pathinfo($vv, PATHINFO_EXTENSION);
                    if($ext == 'css'){
                        $str .= '<link href="'.$baseUrl.$vv.'" rel="stylesheet" type="text/css"/>';
                    }
                    else if($ext == 'js'){
                        $str .= '<script type="text/javascript" src="'.$baseUrl.$vv.'"></script>';
                    }

                    $str .= "\r\n";
                }
            }else{
                $ext = pathinfo($v, PATHINFO_EXTENSION);
                if($ext == 'css'){
                    $str .= '<link href="'.$baseUrl.$v.'" rel="stylesheet" type="text/css"/>';
                }
                else if($ext == 'js'){
                    $str .= '<script type="text/javascript" src="'.$baseUrl.$v.'"></script>';
                }
                $str .= "\r\n";
            }
        }
    }

    return $str;
}

/**
 * 调试函数
 *
 * @access public
 * @param  mxied	$data	调试数据
 * @param  integer	$flag	调用方法
 * @param  integer	$break	程序是否中止执行
 * @return string
 */

function p($data, $flag = 0, $break = 1){

    echo '<pre>';
    if( ! empty($flag)){
        var_dump($data);
    }else{
        print_r($data);
    }
    echo '</pre>';
    if( ! empty($break)){
        exit();
    }
}

/**
 * 保存csv上传图片
 *
 * @param $data
 * @param $path
 */
function saveCSVimg($data, $path = '',$name = null){

    $qData = array();
    $tAd = array();
    foreach ($data as $k => $v){

        if(is_null($name)){
            $name = time().$k;
        }

        $type = '';
        $tA = explode(',', $v);
        if( ! isset($tA[1])) return;

        $content = $tA[1];
        $tA = explode(';', $tA[0]);
        $tS = trim(str_replace('data:', '', $tA[0]));

        switch(strtolower($tS)){

            case 'image/png':
                $type = '.png';
                break;
            case 'image/jpeg':
                $type = '.jpeg';
                break;
            case 'image/gif':
                $type = '.gif';
                break;
            default: return false;
        }
        $name .= $type;

        $fileName = trim($path, '/').'/'.basename($name);
        $content = base64_decode($content);
        if( ! $content) return false;

        if( ! is_dir($path)){
            mkdir($path, 755, true);
        }

        $file = fopen($fileName, "w");
        if( ! $file) return false;
        fwrite($file, $content);
        fclose($file);
        $qData[] = $fileName.'?r='.rand(1, 1000000);
    }

    if( ! $qData){
        return false;
    }
    return $qData;
}

/**
 * 删除字符串中的空格
 * @param $str
 * @return mixed
 */
function trimall($str)
{
    $qian=array(" ","　","\t","\n","\r");
    $hou=array("","","","","");

    return str_replace($qian,$hou,$str);
}

/**
 *  上传图片
 *
 *  @param   string   $path     	上传路径
 *  @param   string   $upload_file  上传表单名称
 *  @param   string   $file_name    上传后的文件名称
 *  @param   string   $max_size     上传的最大占用空间
 *  @return  Array
 */

if( ! function_exists('imageUpload'))
{
    function imageUpload($path, $upload_file, $file_name ='', $thumb = FALSE, $thumbWidth = 250, $thumbHeight = 250)
    {
        if($path == '' || $upload_file == '') return FALSE;
        $ci = & get_instance();
        $path = $path;
        $config = array(
            'file_name' => $file_name,
            'upload_path' => './'.$path,
            'overwrite' => true,
            'allowed_types' => 'gif|jpg|png|jpeg',
            'max_size' => 1024 * 10,
        );
        if( ! is_dir($path)){
            mkdir($path, 0777, TRUE);
        }

        $ci->load->library('upload');
        $ci->upload->initialize($config);

        if($ci->upload->do_upload($upload_file))
        {
            $temp = $ci->upload->data();

            //矫正手机上传的图片
//     		$file = $path.'/'.$temp['file_name'];
//     		$exif = exif_read_data($file);
//     		if( ! empty($exif['Orientation'])){
//     			$image = imagecreatefromjpeg($file);
//     			if($exif['Orientation'] == 3) {
//     				$result = imagerotate($image, 180, 0);
//     				imagejpeg($result, $file, 100);
//     			} elseif($exif['Orientation'] == 6) {
//     				$result = imagerotate($image, -90, 0);
//     				imagejpeg($result, $file, 100);
//     			} elseif($exif['Orientation'] == 8) {
//     				$result = imagerotate($image, 90, 0);
//     				imagejpeg($result, $file, 100);
//     			}
//     			if(isset($result)){
//     				imagedestroy($result);
//     			}
//     			imagedestroy($image);
//     		}

            if($thumb)
            {
                $path1 = $temp['file_path'].'sm';
                //生成缩略图
                imageThumb($path.'/'.$temp['file_name'], $path1, $thumbWidth, $thumbHeight);

                $path1 = $temp['file_path'].'xs';
                imageThumb($path.'/'.$temp['file_name'], $path1, 100, 100);
            }

            return array('status' => TRUE, 'data' => $path.'/'.$temp['file_name'].'?r='.rand(1, 100000));
        }
        else
        {
            $msg_config = array(
                1 => '图片文件过大',
                2 => '没有选择要上传的图片',
                3 => '选择的图片类型错误',
            );
//    		p($ci->upload->display_errors('', ''));
            return array('status' => FALSE, 'data' => @$msg_config[$ci->upload->display_errors('', '')]);
        }
    }
}

/**
 *  上传图片
 *
 *  @param   string   $path     	上传路径
 *  @param   string   $upload_file  上传表单名称
 *  @param   string   $file_name    上传后的文件名称
 *  @return  Array
 */

if( ! function_exists('fileUpload'))
{
    function fileUpload($path, $upload_file, $file_name ='')
    {

        if($path == '' || $upload_file == '') return FALSE;
        $ci = & get_instance();
        $path = $path;
        $config = array(
            'file_name' => $file_name,
            'upload_path' => './'.$path,
            'overwrite' => true,
            'allowed_types' => '*',
        );
        if( ! is_dir($path)){
            mkdir($path, 0777, TRUE);
        }

        $ci->load->library('upload');
        $ci->upload->initialize($config);
        if($ci->upload->do_upload($upload_file)){
            $temp = $ci->upload->data();
            return array('status' => TRUE, 'data' => $path.'/'.$temp['file_name'].'?r='.rand(1, 100000));
        }else{
            $msg_config = array(
                1 => '文件过大',
                2 => '没有选择要上传的文件',
                3 => '选择的文件类型错误',
            );
            return array('status' => FALSE, 'data' => @$msg_config[$ci->upload->display_errors('', '')]);
        }
    }
}

/**
 *  生成缩略图
 *
 *  @param   string   $source     	 原图路径
 *  @param   string   $path         缩略图保存路径
 *  @param   Integer  $width        缩略图宽度
 *  @param   Integer  $height       缩略图高度
 *  @return  fix
 */

if( ! function_exists('imageThumb'))
{
    function imageThumb($source, $path, $width = 150, $height = 150)
    {
        if($source == '' || $path == '') return FALSE;

        $ci = & get_instance();
        $config = array(
            'mage_library' => 'gd2',
            'source_image' => $source,
            'create_thumb' => TRUE,
            'new_image' => $path,
            'width' => $width,
            'height' => $height,
            'maintain_ratio' => TRUE,
            'thumb_marker' => '',
        );

        if( ! is_dir($path))
        {
            mkdir($path, 0777, TRUE);
        }

        $ci->load->library('image_lib');
        $ci->image_lib->initialize($config);
        $fileName = '';
        $tA = explode('/', $source);
        $fileName = $tA[count($tA) - 1];
        $file = trim($path, '/').'/'.$fileName;
        $query = $ci->image_lib->resize();
        if($query){
            return $file;
        }
        return false;
    }
}


/**
 * 获取客服端ip
 *
 */
function getClientIp(){

    $ip = '';
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        $ip=$_SERVER['HTTP_CLIENT_IP'];
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
        $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

/**
 * 发送短信
 * @param string $phone
 * @param string $msg
 * @return bool
 */
function sendSms($phone = '', $msg){
    $tA = getCustomConfig('sms');
    //公共参数(帐号,密码,url地址)
    require APPPATH.'libraries/sms/SmsSendConn.php';
    //南方短信节点url地址
    $url = 'http://api01.monyun.cn:7901/sms/v2/std/';
    //北方短信节点url地址
    //$url = 'http://api02.monyun.cn:7901/sms/v2/std/';
    $smsSendConn = new SmsSendConn($url);
    $data = array();
    $data['userid'] = $tA['username']; //设置账号(必填)
    $data['pwd'] = $tA['passwd']; //设置密码(必填.填写明文密码,如:1234567890)
    $data['mobile'] = $phone; // 设置手机号码 此处只能设置一个手机号码(必填)
    $data['content'] = $msg; // 设置发送短信内容(必填)
    $data['svrtype'] = '47776'; // 业务类型(可选)
    $data['exno'] = ''; // 设置扩展号(可选)
    $data['custid'] = ''; //用户自定义流水编号(可选)
    $data['exdata'] = ''; // 自定义扩展数据(可选)
    try {
        $result = $smsSendConn->singleSend($data);
        if ($result['result'] === 0) {
            return true;
        } else {
//            print_r("单条信息发送失败，错误码：" . $result['result']);
            return false;
        }
    }catch (Exception $e) {
//        print_r($e->getMessage());//输出捕获的异常消息，请根据实际情况，添加异常处理代码
        return false;
    }
    return false;
}

/**
 * 群发 发送短信
 * @param string $phone='13243757111,13243757112' 字符串
 * @param string $msg
 * @return bool
 */
function sendSmsBatch($phone = '', $msg){
    $tA = getCustomConfig('sms');
    //公共参数(帐号,密码,url地址)
    require APPPATH.'libraries/sms/SmsSendConn.php';
    //南方短信节点url地址
    $url = 'http://api01.monyun.cn:7901/sms/v2/std/';
    //北方短信节点url地址
    //$url = 'http://api02.monyun.cn:7901/sms/v2/std/';
    $smsSendConn = new SmsSendConn($url);
    $data = array();
    $data['userid'] = $tA['username']; //设置账号(必填)
    $data['pwd'] = $tA['passwd']; //设置密码(必填.填写明文密码,如:1234567890)
    $data['mobile'] = $phone; // 设置手机号码 此处只能设置一个手机号码(必填)
    $data['content'] = $msg; // 设置发送短信内容(必填)
    $data['svrtype'] = '47776'; // 业务类型(可选)
    $data['exno'] = ''; // 设置扩展号(可选)
    $data['custid'] = ''; //用户自定义流水编号(可选)
    $data['exdata'] = ''; // 自定义扩展数据(可选)
    try {
        $result = $smsSendConn->batchSend($data);
        if ($result['result'] === 0) {
            return true;
        } else {
            print_r("单条信息发送失败，错误码：" . $result['result']);
            return false;
        }
    }catch (Exception $e) {
        print_r($e->getMessage());//输出捕获的异常消息，请根据实际情况，添加异常处理代码
        return false;
    }

    return false;
}

/**
 * 及时聊天
 */
function easemob($easemobName,$easemobword){
    $tA = getCustomConfig('easemob');
    include APPPATH."libraries/emchat/Easemob.class.php";

    $options['client_id'] = $tA['client_id'];
    $options['client_secret'] = $tA['client_secret'];
    $options['org_name'] = $tA['org_name'];
    $options['app_name'] = $tA['app_name'];

    $h = new Easemob($options);

    //注册账号
    $result = $h->createUser($easemobName,$easemobword);

    if(isset($result['error'])){
        return array('status' => 0,'error' => $result['error'],'msg' => '环信注册失败');
    }

    return array('status' => 1,'error' => '','msg' => '环信注册成功');
}

/**
 * 获取默认图片
 */
function getDefaultAds($name){
    return base_url('static/img/cxsm/'.$name.'.png');
}

/**
 * 获取默认图片
 */
function getDefaultImg(){
    return base_url('static/img/no_img.png');
}

/**
 * 获取订单号
 * @return string
 */
function getOrderCode(){
    return date('Ymdhis').rand(100, 999).rand(100, 999);
}

/**
 * 获取图片(包括中小)
 * @param   string $basePath
 * @param   string $type 		(sm|sx)
 * @return	string
 */
function getImage($basePath, $type = ''){

    $data = array(
        'og' => getDefaultImg('og'),
        'sm' => getDefaultImg('sm'),
        'xs' => getDefaultImg('xs'),
    );
    if( ! $basePath){

        if($type){
            return $data[$type];
        }
        return $data;
    }

    $tA = explode('?', $basePath);
    $tA = explode('/', $tA[0]);
    $fileName = $tA[count($tA) - 1];

    $sm = str_replace($fileName, 'sm/'.$fileName, $basePath);
    $xs = str_replace($fileName, 'xs/'.$fileName, $basePath);

    $tA = explode('?', $xs);

    if( ! file_exists($tA[0])){
        $xs = $basePath;
    }

    $tA = explode('?', $sm);
    if( ! file_exists($tA[0])){
        $sm = $basePath;
    }

    $data['og'] = base_url($basePath);
    $data['sm'] = base_url($sm);
    $data['xs'] = base_url($xs);

    if($type){
        return isset($data[$type]) ? $data[$type] : '';
    }

    return $data;
}

/**
 * 生成二维码
 * @param	string	$url	网站
 * @return	void
 */
function code($url){
    include(APPPATH.'libraries/phpqrcode/phpqrcode.php');
    $url = urldecode($url);
    QRcode::png($url);
}

/**
 * 获取所有的直辖市
 */
function getMunicipality(){
    return getCustomConfig('municipality');
}

/**
 * 获取默认头像
 * @param int $type
 * @return string
 */
function getDefaultPortrait($type = 0){

    if ($type == 1){
        return getImage('static/img/default/head.png');
    }else if($type == 2){
        return base_url('static/img/default/merchant_avatar.png'); //商家默认头像
    }else{
        return base_url('static/img/default/head.png');
    }
}

/**
 * 去除数字中的0
 */
function formatNumber($number){

    if(strpos($number, '.00')){
        return str_replace('.00', '', $number);
    }elseif(strpos($number, '.0')){
        return str_replace('.0', '', $number);
    }

    if( ! $number){
        $number = '0';
    }

    return rtrim($number, '0');
}

/**
 * 无定位的时候提示
 * @param integer $type	1：自己未开启定位     2:客户未开启定位
 */
function noPositionPrompt($type = 1){
    static $config = array();

    if( ! $config){
        $config = getCustomConfig('no_position');
    }

    if($type == 1){
        return $config['own'];
    }elseif($type == 2){
        return $config['other'];
    }

    return '';
}

/**
 * 转换时间
 * @param $time
 * @return false|string
 */
function times($time){
    $today = strtotime(date('Y-m-d', time()));
    if($time > $today){
        return date('H:i:s',$time);
    }else{
        return date('Y-m-d',$time);
    }
}

/**
 * 用户激光推送
 * @param 	string 	$title		标题
 * @param 	string 	$content	内容
 * @param 	integer $type		1:指定人推送  2:所有人
 * * @param 	integer $contentType	1：系统消息(所有人)  2：系统消息(指定人)  3：订单消息 4售后订单消息
 * @param 	integer $relationId	order_id(订单消息,售后消息)|message_id(系统消息)
 * @param 	integer $expenseType	1-送货上门 2-到店自取
 * @param 	array 	$users		推送指定的别名
 * @param 	string 	$port		推送的端口
 * @return 	array
 */
function jpush($title, $content, $type = 1, $users = array(), $contentType = 0, $relationId = 0, $expenseType = 0,$sound = 'iOS sound'){

    static $load = false;

    $tA = getCustomConfig('jpush');

    if( ! $contentType){
        $contentType = 1;
    }

    if( ! $load){
        require_once APPPATH.'libraries/jpush-api-php-client-3.5.7/autoload.php';
        $load = true;
    }
    $client = new \JPush\Client($tA['app_key'], $tA['master_secret']);
    $pusher = $client->push();
    $pusher->setPlatform('all');
    $pusher->setNotificationAlert($title);
    $pusher->options(array('apns_production' => true));
    if($type == 2){
        $pusher->addAllAudience();
    }else{
        $pusher->addAlias($users);
    }
    $pusher->message($content, array(
        'title' => $title,
        'content_type' => 'text',
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            'relation_id'=>$relationId
        ),
    ));
    $pusher->iosNotification($content, array(
        'sound' => $sound,
        'badge' => '+1',
        'category' => 'iOS category',
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            'relation_id'=>$relationId
        ),
    ));
    $pusher->androidNotification($content, array(
        'title' => $title,
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            'relation_id'=>$relationId
        ),
    ));

    try {
        $pusher->send();
        $data = array('status' => 1, 'message' => '');
    } catch (\JPush\Exceptions\JPushException $e) {
        $data = array('status' => 0, 'message' => $e->getMessage());
    }

    return $data;
}

/**
 * 商家激光推送
 * @param 	string 	$title		标题
 * @param 	string 	$content	内容
 * @param 	integer $contentType	1：系统消息(所有人)  2：系统消息(指定人)  3：订单消息  4售后订单消息
 * @param 	integer $relationId	order_id(订单消息,售后消息)|message_id(系统消息)
 * @param 	integer $expenseType	1-送货上门 2-到店自取
 * @param 	integer $type		1:指定人推送  2:所有人
 * @param 	array 	$users		推送指定的别名
 * @param 	string 	$port		推送的端口
 * @return 	array
 */
function MerchantJpush($title, $content, $type = 1, $users = array(),$contentType = 0, $relationId = 0, $expenseType = 0,$sound = 'iOS sound',$newOrder = 0){
    static $load = false;
    $tA = getCustomConfig('merchant_jpush');
    if( ! $contentType){
        $contentType = 1;
    }
    if( ! $load){
        require_once APPPATH.'libraries/jpush-api-php-client-3.5.7/autoload.php';
        $load = true;
    }
    $client = new \JPush\Client($tA['app_key'], $tA['master_secret']);
    $pusher = $client->push();
    $pusher->setPlatform('all');
    $pusher->setNotificationAlert($title);
    $pusher->options(array('apns_production' => true));
    if($type == 2){
        $pusher->addAllAudience();
    }else{
        $pusher->addAlias($users);
    }
    $contentType = $contentType.'';
    $relationId = $relationId.'';
    $pusher->message($content, array(
        'title' => $title,
        'content_type' => 'text',
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            "new_order"=>$newOrder,
            'relation_id'=>$relationId
        ),
    ));
    $pusher->iosNotification($content, array(
        'sound' => $sound,
        'badge' => '+1',
        'category' => 'iOS category',
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            'relation_id'=>$relationId
        ),
    ));
    $pusher->androidNotification($content, array(
        'title' => $title,
        'extras' => array(
            "type"=>$contentType,
            "expense_type"=>$expenseType,
            "new_order"=>$newOrder,
            'relation_id'=>$relationId
        ),
    ));

    try {

        $pusher->send();
        $data = array('status' => 1, 'message' => '');
    } catch (\JPush\Exceptions\JPushException $e) {
        $data = array('status' => 0, 'message' => $e->getMessage());
    }

    return $data;
}

/**
 * 配送员激光推送
 * @param 	string 	$title		标题
 * @param 	string 	$content	内容
 * @param 	integer $type		1:指定人推送  2:所有人
 * * @param 	integer $contentType	1：平台推送 2：系统消息
 * @param 	array 	$users		推送指定的别名
 * @param 	string 	$port		推送的端口
 * @param 	string 	$newOrder	0普通	1新订单 2人工派单 3人工改派
 * @return 	array
 */
function deliverymanJpush($title, $content, $type = 1, $users = array(), $contentType = 0, $sound = 'iOS sound',$newOrder = 0){

    static $load = false;

    $tA = getCustomConfig('deliveryman_jpush');

    if( ! $contentType){
        $contentType = 1;
    }

    if( ! $load){
        require_once APPPATH.'libraries/jpush-api-php-client-3.5.7/autoload.php';
        $load = true;
    }
    $client = new \JPush\Client($tA['app_key'], $tA['master_secret']);
    $pusher = $client->push();
    $pusher->setPlatform('all');
    $pusher->setNotificationAlert($title);
    $pusher->options(array('apns_production' => true));
    if($type == 2){
        $pusher->addAllAudience();
    }else{
        $pusher->addAlias($users);
    }
    $pusher->message($content, array(
        'title' => $title,
        'content_type' => 'text',
        'extras' => array(
            "type"=>$contentType,
            "new_order"=>$newOrder,
        ),
    ));
    $pusher->iosNotification($content, array(
        'sound' => $sound,
        'badge' => '+1',
        'category' => 'iOS category',
        'extras' => array(
            "type"=>$contentType,
        ),
    ));
    $pusher->androidNotification($content, array(
        'title' => $title,
        'extras' => array(
            "type"=>$contentType,
            "new_order"=>$newOrder,
        ),
    ));

    try {
        $pusher->send();
        $data = array('status' => 1, 'message' => '');
    } catch (\JPush\Exceptions\JPushException $e) {
        $data = array('status' => 0, 'message' => $e->getMessage());
    }

    return $data;
}



/**
 * 获取post值
 * @param  string $key
 * @return mixed
 */
function post($key){
    $ci = get_instance();
    return $ci->input->post($key);
}

/**
 * 获取get值
 * @param  string $key
 * @return mixed
 */
function get($key){
    $ci = get_instance();
    return $ci->input->get($key);
}

/**
 * 获取云通讯id
 */
function getTencentId(){
    return uniqid().rand(100, 999).rand(1000, 9999);
}

/**
 * 加载及时通讯api
 */
function loadTencentObj(){
    static $api = null;
    if( ! $api){
        require APPPATH.'libraries/tencent_chat_sdk/TimRestApi.php';
        $api = createRestAPI();
        $api->generate_user_sig();
    }

    return $api;
}

/**
 * 保存临时文件夹中的图片
 * @param	string 		$source	图片路径
 * @param	string 		$path	保存路径
 * @param	boolean 	$thu	是否需要保存缩略图
 * @param	integer 	$width	最大宽度
 * @param	integer 	$height	最大高度
 * @return	string
 */
function saveTempImg($source, $path = '', $thu = true, $width = 800, $height = 800){

    $tA = explode('?', str_replace(base_url(), '/', $source));
    $source = trim($tA[0], '/');

    $tS = imageThumb($source, $path, $width, $height);
    if( ! $tS){
        return false;
    }

    if($thu){
        $tP = trim($path, '/').'/sm';
        imageThumb($source, $tP, 250, 250);
        $tP = trim($path, '/').'/xs';
        imageThumb($source, $tP, 100, 100);

    }

    unlink($source);
    return $tS.'?r='.rand(1, 100000);
}

/**
 * 保存编辑中的临时文件
 * @param 	string $detials
 * @return	string
 */
function saveEditerTempImg($content, $contentImgPath){

    $contentImg = array();
    $content = str_replace(base_url(), '{base_url."}', $content);
    $tA = explode('{base_url', $content);
    $content = '';
    foreach ($tA as $k => $v){
        if(strpos($v, '."}') === 0){
            $tS = str_replace('."}', '', $v);
            $tAA = explode('"', $tS);
            $img = $tAA[0];
            if(strpos($img, 'temp') > 0){

                if( ! file_exists($img) && ! array_key_exists($img, $contentImg)){
                    return false;
                }

                if( ! array_key_exists($img, $contentImg)){
                    $newImg = imageThumb($img, $contentImgPath, 800, 800);
                    if($newImg === false){
                        return false;
                    }
                    @unlink($img);
                }else{
                    $newImg = $contentImg[$img];
                }

                $content .= str_replace('."}'.$img, '{base_url}'.$newImg, $v);
                $contentImg[$img] = $newImg;
            }else{
                $content .= str_replace('."}', '{base_url}', $v);
                $contentImg[$img] = $img;
            }
        }else{
            $content .= $v;
        }
    }

    return $content;
}

/**
 * 移动文件到新文件
 * @param array     $images
 * @param string    $path
 * @return array
 * @throws Exception
 */
function moveImage($images,$path){
    if ( ! is_array($images)){
        throw new Exception("请使用图片地址的数组<moveImage>");
    }
    $imgPath = array();
    foreach ($images as $k=>$v){
        //寻找是临时文件夹的
        if (stripos($v,'temp') !== FALSE){
            //去掉未的？

            //是否有http 去掉
            if (stripos($v, base_url()) !== false){
                $v = str_replace(base_url(), '', $v);
            }

            //是否有 ? 去掉
            if (stripos($v, '?') !== false){
                $v = strstr($v, '?', true);
            }

            if ( ! file_exists($v)){
                continue;
            }

            //获取文件名
            $tI = explode('/', $v);
            $filename = $tI[count($tI)-1];
            //文件新地址
            //$path = 'uploads/shop/'.$tId.'/';

            if ( ! file_exists($path)){
                mkdir($path,0777,true);
            }
            if( ! file_exists($path.'sm/')){
                mkdir($path.'sm/',0777,true);
            }
            if( ! file_exists($path.'xs/')){
                mkdir($path.'xs/',0777,true);
            }

            $newFile = $path.$filename;
            $pathsm  = $path.'sm/'.$filename;
            $pathxs  = $path.'xs/'.$filename;
            if (file_exists($v)){
                moveFile($v, $newFile);
            }

            //缩略图地址
            $sm = str_replace($filename, 'sm/'.$filename, $v);
            $xs = str_replace($filename, 'xs/'.$filename, $v);
            if (file_exists($sm)){
                moveFile($sm, $pathsm);
            }
            if (file_exists($xs)){
                moveFile($xs, $pathxs);
            }

            //将文件地址保存起来
            $imgPath[] = $newFile.'?r='.rand(0,999);
        }else{
            $imgPath[] = $v;
        }
    }

    if ( ! $imgPath){
        //throw new Exception("你保存的图片好像临时文件都没有了<moveImage>");
    }
    return $imgPath;
}
/**
 * 移动文件到新地方
 * @param unknown $file
 * @param unknown $newFile
 */
function moveFile($file,$newFile){
    copy($file,$newFile); //拷贝到新目录
    unlink($file); //删除旧目录下的文件
}

/**
 * @name php获取中文字符拼音首字母
 * @param $str
 * @return null|string
 * @author 潘军伟<panjunwei@ruiec.cn>
 * @time 2015-09-14 17:58:14
 */
function getFirstCharter($str){

    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312//IGNORE', $str);
//	$s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';
    return null;
}

/**
 * 根据详细地址解析坐标
 */
function getLocation($address){
    $url="http://api.map.baidu.com/geocoder/v2/?address='".$address."'&output=xml&ak=IcjizDVNXGBRCZeZ3y3Z8GvRBXccrIEz&callback=showLocation";
    if(function_exists('file_get_contents')){
        $file_contents = file_get_contents($url);
    }else{
        $ch = curl_init();
        $timeout = 5000;
        $header = array (

        );
        //$header=Array("authenticate: e021d10c3276983bb15c4325d5dc452b","version:ems_track_cn_1.0");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  //设置头信息的地方
        curl_setopt($ch, CURLOPT_HTTPHEADER, 1);
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }


    $xml1 = simplexml_load_string($file_contents);
    $json  = json_encode($xml1);
    $configData = json_decode($json, true);
    if($configData['status'] == 0){
        return $configData['result']['location'];
    }
    return false;
}

/**
 * Valid Email
 *
 * @param	string
 * @return	bool
 */
function valid_email($str)
{
    if (function_exists('idn_to_ascii') && $atpos = strpos($str, '@'))
    {
        $str = substr($str, 0, ++$atpos).idn_to_ascii(substr($str, $atpos));
    }

    return (bool) filter_var($str, FILTER_VALIDATE_EMAIL);
}

/**
 * 验证手机号码
 *
 * @param	string
 * @return	boolean
 */
function valid_mobile($str){

    return (bool) preg_match('/^0?1[1|3|4|5|7|8|9][0-9]\d{8}$/', $str);
}

/**
 * 计算商品优惠的价格
 * @param $price            int         商品价格(50)
 * @param $totalPrice       int         除数(100)
 * @param $interestRate     float       被除数利率(10)
 * @return float (45)
 */
function favourablePrices($price, $totalPrice, $interestRate){
    if ($totalPrice == 0 || $interestRate == 0){
        return $price;
    }
    $p = (1-$interestRate/$totalPrice)*$price;
    return round($p, 2);
}

function showLog($str){
    file_put_contents('1.txt', PHP_EOL.date('Y-m-d H:i:s', time()), FILE_APPEND);
    file_put_contents('1.txt', print_r($str, true), FILE_APPEND);
}